/// 
/// MaDAson - Toolkit for Model Driven Software Development
/// 
/// Copyright [2006] Marcus Lankenau
/// 
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///  
///     http://www.apache.org/licenses/LICENSE-2.0
///  
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
/// 

using System;
using System.Collections.Generic;
using System.Text;

namespace Madason.TemplateCompiler
{
	public class TokenlistOptimizer
	{
		protected static bool EndsWithLineBreak(string text)
		{
			int i = text.Length - 1;
			while (i >= 0)
			{
				if (text[i] == '\n') return true;
				if (text[i] != '\r' && text[i] != '\t' && text[i] != ' ')
					return false;
				i--;
			}
			return false;
		}

		protected static bool StartsWithLineBreak(string text)
		{
			int i = 0;
			while (i < text.Length)
			{
				if (text[i] == '\n') return true;
				if (text[i] != '\r' && text[i] != '\t' && text[i] != ' ')
					return false;
				i++;
			}
			return false;
		}


		public static void OptimizeLineBreaks(List<Token> tokenList)
		{
			for (int i = 0; i < tokenList.Count; i++)
			{
				bool isFirst = (i == 0);
				bool isLast = (i == tokenList.Count - 1);

				Token token = tokenList[i];
				if (!isFirst && !isLast)
				{
					if (EndsWithLineBreak(tokenList[i-1].Content) &&
						StartsWithLineBreak(tokenList[i+1].Content))
					{
						int pos = tokenList[i-1].Content.LastIndexOf("\n");
						tokenList[i - 1].Content = tokenList[i - 1].Content.Substring(0, pos);
					}
				}
			}
		}
	}
}
